package test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.brother.model.AlarmType;
import com.brother.model.DataFlag;
import com.brother.realtime.Command;
import com.brother.realtime.ConfigRequestStatusCommand;
import com.brother.realtime.ConfigStatusCommand;
import com.brother.realtime.DataCommand;
import com.brother.realtime.GsnCommand;
import com.brother.realtime.HeartbreakCommand;
import com.brother.realtime.LostSignalCommand;
import com.brother.realtime.MutilDataCommand;
import com.brother.realtime.ReqTrackerVerCommand;
import com.brother.realtime.RequestAddressCommand;
import com.brother.realtime.ThirdPartyGEOCommand;
import com.brother.realtime.ThirdPartyLowBatteryCommand;
import com.brother.realtime.ThirdPartyOverSpeedCommand;
import com.brother.realtime.ThirdPartySOSCommand;
import com.brother.realtime.UpgradeFrameStatusCommand;
import com.brother.util.CommonProperties;

public class CommandParser {

private long lastRecievedTime = System.currentTimeMillis();

private long lostSignalLimit = 20000; // The time-span for setting lost signal. 

/**
 * 日/月/年
 * date：01/12/10    //日/月/年
 * time：13:25:35    //时：分：秒
 */
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

/**
 * 第三方的协议时间格式
 */
private SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyMMdd HHmmss");


private String remoteAddr = "";
private String IMEI = null;

	public boolean isStopped() {
		return false;
	}

	public CommandParser(){
	}
	private Logger log = Logger.getLogger(this.getClass());	
	private List<Command> cmds = new ArrayList<Command>();
	
	public Command readOneCommand(StringBuffer sb){
		if(IMEI != null){ //  it is the third party proctocal
			if(cmds.size() > 0){ //  There is cmd left.
				return cmds.remove(0);
			}
		}
		try {
				
				char c = (char)sb.charAt(0);
				if(c == '!'){
					try{
						return parseCommand(sb);
					}catch(Exception e){
						log.error("parse command error! "+remoteAddr+","+this.IMEI+",input:"+sb.toString(),e);
					}
				}
				if(c == '#' && (sb.length() > 1) && (sb.charAt(0) == '#')){
				//	#356896031498455,CMD-T,A,DATE:110107,TIME:061607,LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,0-0-0-0-85-30,000#
					try{
						return parseThirdPartyCMD(sb);
					}catch(Exception e){
						log.error("parse command error for third party! "+remoteAddr+","+this.IMEI+",input:"+sb.toString(),e);
					}
				}
			
		} catch (Exception e) {
			log.error(e);
			return new LostSignalCommand();
		}
		return null;
	}
	
	/**	#356896031498455,CMD-T,A,DATE:110107,TIME:061607,
	 * LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,
	 * 0-0-0-0-85-30,000#
	 * @param sb
	 * @throws ParseException 
	 */
	private Command parseThirdPartyCMD(StringBuffer sb) throws ParseException {
		String line = sb.toString();
		log.debug(this.IMEI+",Third party cmd:"+line);
		sb.delete(0, sb.length());
		line = line.replaceAll("[#]", "");
		String[] cmdsText = line.split(","); 
		if(IMEI == null){
			IMEI = cmdsText[0];
			GsnCommand cmd = new GsnCommand();
			cmd.setUserTrackerId(IMEI);
			cmds.add(cmd);
		}
		//  ========== 不知道的协议, #27/01/11,14:32:37,12.884873,74.843262,0,0#
		if(cmdsText[0].indexOf("/") > -1){
			return unknowData(cmdsText);
		}
		//  ========== 不知道的协议
		// 非地理位置数据
		if(!cmdsText[1].equals(Command.THIRD_PARTY_CMD_T)){
			parseThridPartyStatus(cmdsText);
		}
		if(cmdsText.length < 3){
			return cmds.remove(0); // 先返回第一条，可能是imei号
		}
		if(!cmdsText[2].equals("A")){ // gps信号没有修复好
			if(cmds.size() == 0)
				cmds.add(new HeartbreakCommand(2000l));
			return cmds.remove(0); // 先返回第一条，可能是imei号
		}
		DataCommand cmd = new DataCommand();
		String data = cmdsText[5];
		data = data.substring(4);
		cmd.setLatOrient(data.substring(data.length()-1));
		cmd.setLat(Float.parseFloat(data.substring(0, data.length() -1)));
		cmd.setOrig_lat(data);
		
		data = cmdsText[6];
		data = data.substring(4);
		cmd.setLngOrient(data.substring(data.length()-1));
		cmd.setLng(Float.parseFloat(data.substring(0, data.length() -1)));				
		cmd.setOrig_lng(data);
		
		data = cmdsText[7];
		data = data.substring(6);
		cmd.setSpeed(Float.parseFloat(data));
		
	   //System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & DataFlag.OVERSPEED)+"  data:"+data);
		cmd.setFlag(AlarmType.GPS_Pos.toString());
		
		data = cmdsText[3]; // DATE:110107
		data = data.substring(5);
		
		String d2 = cmdsText[4]; // TIME:061607
		d2 = d2.substring(5);
		Date date = dateFormat2.parse(data + " "+d2);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);
		
		String[] stats = cmdsText[8].split("-");
		if(stats.length <= 3){ // For TL201: In the format of XX-YY. XX means the battery, the top is 100.YY means the GSM signal, the top is 31.
			cmd.setBattery(new String(stats[0]));
			cmd.setGsm(new Integer(stats[1]));
		}else if(stats.length == 5){ 
			/*For  TL108: In the format  of A-B-C-XX-YY. A=1 means ACC on,  A=0 means ACC off. 
			B=1 means tracker get power for the car battery, B=0 means tracker lose power
			from car battery. C=1  means door open, C=0  means door close. 
			XX means the battery, the top  is  100. YY means the GSM signal, the top is 31.*/
			if(stats[0].equals("1")){
				cmd.setAccStat(1);
			}else if(stats[0].equals("0")){
				cmd.setAccStat(0);
			}
			if(stats[1].equals("0")){
				cmd.setFlag(AlarmType.External_Power_Lost.name());
			}
			if(stats[2].equals("1")){
				cmd.setDoorStat(1);
			}else if(stats[2].equals("0")){
				cmd.setDoorStat(0);
			}
			cmd.setBattery(new String(stats[3]));
			cmd.setGsm(new Integer(stats[4]));
		}else if(stats.length == 6){ 
			/*For  TL108: In the format  of X-X-X-X-BB-YY. BB means the battery, the top  is  100. YY means the GSM signal, the top is 31.*/
			cmd.setBattery(new String(stats[4]));
			cmd.setGsm(new Integer(stats[5]));
		}
		if(cmdsText.length == 10 && cmdsText[9].length() > 0)
			cmd.setOrient(cmdsText[9]);
		else
			cmd.setOrient("0");
		
		cmds.add(cmd);
		
		return cmds.remove(0);
	}
	
	/**#356896031498455,CMD-T,A,DATE:110107,TIME:061607,
	 * LAT:22.6474566N,LOT:114.0310116E,Speed:000.0,
	 * 0-0-0-0-85-30,000#
	 * @param cmdsText
	 * @return
	 */
	/**
	 * @param cmdsText
	 * @return
	 */
	private void parseThridPartyStatus(String[] cmdsText) {
		
		if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_X)){
			cmds.add(new HeartbreakCommand(2000l));
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_A)){
			ThirdPartySOSCommand cmd = new ThirdPartySOSCommand();
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_A1)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_A2)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_A3)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_A4)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_A5)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_ALM_B)){
			ThirdPartyGEOCommand cmd = new ThirdPartyGEOCommand();
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_ALM_C)){
			ThirdPartyOverSpeedCommand cmd = new ThirdPartyOverSpeedCommand();
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_ALM_D)){
			ThirdPartyLowBatteryCommand cmd = new ThirdPartyLowBatteryCommand();
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_C)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_ERROR)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_F)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_H)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_I)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_J)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_L)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_N)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_O)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_T0)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_T1)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_U0)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}else if(cmdsText[1].equals(Command.THIRD_PARTY_CMD_U1)){
			ConfigStatusCommand cmd = new ConfigStatusCommand();
			cmd.setText(cmdsText[1]);
			cmd.setStatus("ok");
			cmds.add(cmd);
		}
		
	}

	/**#27/01/11,14:32:37,12.884873,74.843262,0,0#
	 * @param cmdsText
	 * @return
	 * @throws ParseException 
	 */
	private Command unknowData(String[] cmdsText) throws ParseException {
		DataCommand cmd = new DataCommand();
		String data = cmdsText[2];
		cmd.setLat(Float.parseFloat(data));
		cmd.setLatOrient(cmd.getLat()>0 ? "N":"S");
		cmd.setOrig_lat(data+cmd.getLatOrient());
		
		data = cmdsText[3];
		cmd.setLng(Float.parseFloat(data));		
		cmd.setLngOrient(cmd.getLng() > 0?"E":"W");
		cmd.setOrig_lng(data+cmd.getLngOrient());
		
		data = cmdsText[4];
		cmd.setSpeed(Float.parseFloat(data));
		
		data = cmdsText[0]; // 27/01/11
		String d2 = cmdsText[1]; // 14:32:37
		Date date = dateFormat.parse(data + " "+d2);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);
		
		//System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & DataFlag.OVERSPEED)+"  data:"+data);
			data = cmdsText[5]; // flag
		
		  //byte flag = HexString2Bytes(data)[0];	
			
		   if(data.equals(DataFlag.INPUT_1)){
			   cmd.setFlag(AlarmType.Input_1.toString());
		   }
		   if(data.equals(DataFlag.INPUT_2)){
			   cmd.setFlag(AlarmType.Input_2.toString());
		   }
		   if(data.equals(DataFlag.INPUT_3)){
			   cmd.setFlag(AlarmType.Input_3.toString());
		   }
		   if(data.equals(DataFlag.OVERSPEED)){
			   cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
		   }
		   if(data.equals(DataFlag.GEO)){
			   cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
		   }
		   if(data.equals(DataFlag.EXT_POWER)){
			   cmd.setFlag(AlarmType.External_Power_Lost.toString());
		   }
		   if(data.equals(DataFlag.LOW_POWER_ALARM)){
			   cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
		   }
		   if(data.equals(DataFlag.INPUT_4)){
			   cmd.setFlag(AlarmType.Input_4.toString());
		   }else if(data.equals(DataFlag.INPUT_5)){
			   cmd.setFlag(AlarmType.Input_5.toString());
		   }else if(data.equals(DataFlag.ACC_ON)){
			   cmd.setAccStat(1);
			   cmd.setFlag(AlarmType.ACC_ON.toString());
		   }else if(data.equals(DataFlag.ACC_OFF)){
			   cmd.setAccStat(0);
			   cmd.setFlag(AlarmType.ACC_OFF.toString());
		   }else if(data.equals(DataFlag.SIREN_ALARM)){
			   cmd.setFlag(AlarmType.SIREN.toString());
		   }else if(data.equals(DataFlag.SOS)){
			   cmd.setFlag(AlarmType.SOS_Alarm.toString());
		   }else if(data.equals(DataFlag.DOOR_OPENED)){
			   cmd.setDoorStat(1);
			   cmd.setFlag(AlarmType.DOOR_OPENED.toString());
		   }else if(data.equals(DataFlag.DOOR_CLOSED)){
			   cmd.setDoorStat(0);
			   cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
		   }
		   //System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & DataFlag.OVERSPEED)+"  data:"+data);
		   if((cmd.getFlag() == null)){
			   cmd.setFlag(AlarmType.GPS_Pos.toString());
		   }
		
		return cmd;
	}

	private Command parseCommand(StringBuffer sb) {
		try{
		String line = sb.toString();
		sb.delete(0, sb.length());
		if(log.isDebugEnabled()){
			log.debug(remoteAddr+","+this.IMEI+",parse command:"+line);
		}
		line = line.replaceAll("[!;]", "");
		if(line.startsWith(Command.CMD_TYPE_MUTIL_DATA)){
				line = line.substring(2); 
				String[] cmdsText = line.split("#"); 
				// 多条数据：非固定（1-15条）
				/*!B,data1#data2#data3#data4#data5#data6#data7#data8#data9#data10#data11#data12#data13#data14#data15#;
				data1: date,time,lat,lot,speed,flag*/
				MutilDataCommand mutil = new MutilDataCommand();
				for(int i=0; i < cmdsText.length; i++){
					String l = cmdsText[i];
					String[] datas = l.split(",");
					mutil.addCmd(this.parseMutilData(datas));
				}
				return mutil;
		}
		
		String[] datas = line.split(",");
		
			if(datas[0].equals(Command.CMD_TYPE_GSN)){
				GsnCommand cmd = new GsnCommand();
				cmd.setUserTrackerId(datas[1]);
				this.IMEI = datas[1];
				return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_DATA)){
				
				DataCommand cmd = new DataCommand();
				String data = datas[1];
				cmd.setLatOrient(data.substring(data.length()-1));
				cmd.setLat(Float.parseFloat(data.substring(0, data.length() -1)));
				cmd.setOrig_lat(data);
				
				data = datas[2];
				cmd.setLngOrient(data.substring(data.length()-1));
				cmd.setLng(Float.parseFloat(data.substring(0, data.length() -1)));				
				cmd.setOrig_lng(data);
				
				cmd.setSpeed(Float.parseFloat(datas[3]));
				
				data = datas[4]; // flag
				
			  //byte flag = HexString2Bytes(data)[0];	
				
			   if(data.equals(DataFlag.INPUT_1)){
				   cmd.setFlag(AlarmType.Input_1.toString());
			   }
			   if(data.equals(DataFlag.INPUT_2)){
				   cmd.setFlag(AlarmType.Input_2.toString());
			   }
			   if(data.equals(DataFlag.INPUT_3)){
				   cmd.setFlag(AlarmType.Input_3.toString());
			   }
			   if(data.equals(DataFlag.OVERSPEED)){
				   cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
			   }
			   if(data.equals(DataFlag.GEO)){
				   cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
			   }
			   if(data.equals(DataFlag.EXT_POWER)){
				   cmd.setFlag(AlarmType.External_Power_Lost.toString());
			   }
			   if(data.equals(DataFlag.LOW_POWER_ALARM)){
				   cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
			   }
			   if(data.equals(DataFlag.INPUT_4)){
				   cmd.setFlag(AlarmType.Input_4.toString());
			   }else if(data.equals(DataFlag.INPUT_5)){
				   cmd.setFlag(AlarmType.Input_5.toString());
			   }else if(data.equals(DataFlag.ACC_ON)){
				   cmd.setAccStat(1);
				   cmd.setFlag(AlarmType.ACC_ON.toString());
			   }else if(data.equals(DataFlag.ACC_OFF)){
				   cmd.setAccStat(0);
				   cmd.setFlag(AlarmType.ACC_OFF.toString());
			   }else if(data.equals(DataFlag.SIREN_ALARM)){
				   cmd.setFlag(AlarmType.SIREN.toString());
			   }else if(data.equals(DataFlag.SOS)){
				   cmd.setFlag(AlarmType.SOS_Alarm.toString());
			   }else if(data.equals(DataFlag.DOOR_OPENED)){
				   cmd.setDoorStat(1);
				   cmd.setFlag(AlarmType.DOOR_OPENED.toString());
			   }else if(data.equals(DataFlag.DOOR_CLOSED)){
				   cmd.setDoorStat(0);
				   cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
			   }
			   //System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & DataFlag.OVERSPEED)+"  data:"+data);
			   if((cmd.getFlag() == null)){
				   cmd.setFlag(AlarmType.GPS_Pos.toString());
			   }
				
				return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_SINGLE_DATA)){
				
				return this.parseSigleData(datas);
			}else if(datas[0].equals(Command.CMD_TYPE_CONFIG_STATUS)){
				ConfigStatusCommand cmd = new ConfigStatusCommand();
				cmd.setStatus(datas[1]);
				return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_CONFIG_REQUEST_STATUS)){
				ConfigRequestStatusCommand cmd = new ConfigRequestStatusCommand();
				String text = "";
				for(int i = 1;i <=9; i++){
					text = text + datas[i]+",";
				}
				text = text.substring(0, text.length() - 1);
				cmd.setStatus(text);
				return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_REQUEST_ADDRESS)){
				RequestAddressCommand cmd = new RequestAddressCommand();
		        cmd.setLat(datas[1]);
		        cmd.setLng(datas[2]);
		        return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_HEART_BREAK)){
				return new HeartbreakCommand(1000);
			}else if(datas[0].equals(Command.CMD_TYPE_REQ_TRACKER_VERSION)){
				ReqTrackerVerCommand cmd = new ReqTrackerVerCommand();
				cmd.setVersion(datas[1]);
				cmd.setCsq(datas[2]);
				return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_UPGRADE_FRAME_OK)){
				UpgradeFrameStatusCommand cmd = new UpgradeFrameStatusCommand();
				cmd.setFrameAll(Integer.parseInt(datas[1], 16));
				cmd.setFrame(Integer.parseInt(datas[2], 16));
				cmd.setStatus(datas[3]);
				return cmd;
			}else if(datas[0].equals(Command.CMD_TYPE_UPGRADE_FRAME_ERROR)){
				UpgradeFrameStatusCommand cmd = new UpgradeFrameStatusCommand();
				cmd.setFrameAll(Integer.parseInt(datas[1], 16));
				cmd.setFrame(Integer.parseInt(datas[2], 16));
				cmd.setStatus(datas[3]);
				return cmd;
			}
		}catch(Exception e){
			log.error(e);
			return null;
		}
		
		return null;
	}
	
	
	private DataCommand parseMutilData(String[] datas) throws ParseException {
		/**多条数据里的一条：
		 * date,time,lat,lot,speed,flag;
		 * 01/12/10,13:25:35,22.641724,114.023666,000.1,0;
		 * date：01/12/10    //日/月/年
		 * time：13:25:35    //时：分：秒
		 * lat ：22.641724   //实数
		 * lot ：114.023666
		 * speed：000.1     
		 * flag：0
		 */
		DataCommand cmd = new DataCommand();
		Date date = this.dateFormat.parse(datas[0]+" "+datas[1]);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);
		
		cmd.setLat(Float.parseFloat( datas[2]));
		cmd.setOrig_lat(datas[2]);
		if(cmd.getLat() < 0){
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		}else{
			cmd.setLatOrient("N");
		}
		cmd.setLng(Float.parseFloat(datas[3]));		
		cmd.setOrig_lng(datas[3]);
		if(cmd.getLng() < 0){
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		}else{
			cmd.setLngOrient("E");
		}
		
		cmd.setSpeed(Float.parseFloat(datas[4]));
//		cmd.setOrient(datas[6]);
		
		String data = datas[5]; // flag
		
	  //byte flag = HexString2Bytes(data)[0];	
		
	   if(data.equals(DataFlag.INPUT_1)){
		   cmd.setFlag(AlarmType.Input_1.toString());
	   }
	   if(data.equals(DataFlag.INPUT_2)){
		   cmd.setFlag(AlarmType.Input_2.toString());
	   }
	   if(data.equals(DataFlag.INPUT_3)){
		   cmd.setFlag(AlarmType.Input_3.toString());
	   }
	   if(data.equals(DataFlag.OVERSPEED)){
		   cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
	   }
	   if(data.equals(DataFlag.GEO)){
		   cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
	   }
	   if(data.equals(DataFlag.EXT_POWER)){
		   cmd.setFlag(AlarmType.External_Power_Lost.toString());
	   }
	   if(data.equals(DataFlag.LOW_POWER_ALARM)){
		   cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
	   }
	   
	   if(data.equals(DataFlag.INPUT_4)){
		   cmd.setFlag(AlarmType.Input_4.toString());
	   }else if(data.equals(DataFlag.INPUT_5)){
		   cmd.setFlag(AlarmType.Input_5.toString());
	   }else if(data.equals(DataFlag.ACC_ON)){
		   cmd.setAccStat(1);
		   cmd.setFlag(AlarmType.ACC_ON.toString());
	   }else if(data.equals(DataFlag.ACC_OFF)){
		   cmd.setAccStat(0);
		   cmd.setFlag(AlarmType.ACC_OFF.toString());
	   }else if(data.equals(DataFlag.SIREN_ALARM)){
		   cmd.setFlag(AlarmType.SIREN.toString());
	   }else if(data.equals(DataFlag.SOS)){
		   cmd.setFlag(AlarmType.SOS_Alarm.toString());
	   }else if(data.equals(DataFlag.DOOR_OPENED)){
		   cmd.setDoorStat(1);
		   cmd.setFlag(AlarmType.DOOR_OPENED.toString());
	   }else if(data.equals(DataFlag.DOOR_CLOSED)){
		   cmd.setDoorStat(0);
		   cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
	   }
	   
	   //System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & DataFlag.OVERSPEED)+"  data:"+data);
	   if((cmd.getFlag() == null)){
		   cmd.setFlag(AlarmType.GPS_Pos.toString());
	   }
		
		return cmd;
	}

	private DataCommand parseSigleData(String[] datas) throws ParseException {
		/**单条数据：
		 * !A,date,time,lat,lot,speed,degrees,flag;
		 * !A,01/12/10,13:25:35,22.641724,114.023666,000.1,281.6,0;
		 * date：01/12/10    //日/月/年
		 * time：13:25:35    //时：分：秒
		 * lat ：22.641724   //实数
		 * lot ：114.023666
		 * speed：000.1     
		 * degrees：281.6
		 * flag：0
		 */
		DataCommand cmd = new DataCommand();
		Date date = this.dateFormat.parse(datas[1]+" "+datas[2]);
		date.setHours(date.getHours() + 8);
		cmd.setDate(date);
		
		cmd.setLat(Float.parseFloat( datas[3]));
		cmd.setOrig_lat(datas[3]);
		if(cmd.getLat() < 0){
			cmd.setLatOrient("S");
			cmd.setLat(-cmd.getLat());
		}else{
			cmd.setLatOrient("N");
		}
		cmd.setLng(Float.parseFloat(datas[4]));		
		cmd.setOrig_lng(datas[4]);
		if(cmd.getLng() < 0){
			cmd.setLngOrient("W");
			cmd.setLng(-cmd.getLng());
		}else{
			cmd.setLngOrient("E");
		}
		
		cmd.setSpeed(Float.parseFloat(datas[5]));
		cmd.setOrient(datas[6]);
		
		String data = datas[7]; // flag
		
	  //byte flag = HexString2Bytes(data)[0];	
		
	   if(data.equals(DataFlag.INPUT_1)){
		   cmd.setFlag(AlarmType.Input_1.toString());
	   }
	   if(data.equals(DataFlag.INPUT_2)){
		   cmd.setFlag(AlarmType.Input_2.toString());
	   }
	   if(data.equals(DataFlag.INPUT_3)){
		   cmd.setFlag(AlarmType.Input_3.toString());
	   }
	   if(data.equals(DataFlag.OVERSPEED)){
		   cmd.setFlag(AlarmType.Over_Speed_Alarm.toString());
	   }
	   if(data.equals(DataFlag.GEO)){
		   cmd.setFlag(AlarmType.Geo_Fence_Alarm.toString());
	   }
	   if(data.equals(DataFlag.EXT_POWER)){
		   cmd.setFlag(AlarmType.External_Power_Lost.toString());
	   }
	   if(data.equals(DataFlag.LOW_POWER_ALARM)){
		   cmd.setFlag(AlarmType.Low_Power_Alarm.toString());
	   }
	   if(data.equals(DataFlag.INPUT_4)){
		   cmd.setFlag(AlarmType.Input_4.toString());
	   }else if(data.equals(DataFlag.INPUT_5)){
		   cmd.setFlag(AlarmType.Input_5.toString());
	   }else if(data.equals(DataFlag.ACC_ON)){
		   cmd.setAccStat(1);
		   cmd.setFlag(AlarmType.ACC_ON.toString());
	   }else if(data.equals(DataFlag.ACC_OFF)){
		   cmd.setAccStat(0);
		   cmd.setFlag(AlarmType.ACC_OFF.toString());
	   }else if(data.equals(DataFlag.SIREN_ALARM)){
		   cmd.setFlag(AlarmType.SIREN.toString());
	   }else if(data.equals(DataFlag.SOS)){
		   cmd.setFlag(AlarmType.SOS_Alarm.toString());
	   }else if(data.equals(DataFlag.DOOR_OPENED)){
		   cmd.setDoorStat(1);
		   cmd.setFlag(AlarmType.DOOR_OPENED.toString());
	   }else if(data.equals(DataFlag.DOOR_CLOSED)){
		   cmd.setDoorStat(0);
		   cmd.setFlag(AlarmType.DOOR_CLOSED.toString());
	   }
	   //System.out.println("alarm type:" + cmd.getFlag()+"  fl:"+(flag & DataFlag.OVERSPEED)+"  data:"+data);
	   if((cmd.getFlag() == null)){
		   cmd.setFlag(AlarmType.GPS_Pos.toString());
	   }
		
		return cmd;
	}

	public  byte uniteBytes(byte src0, byte src1) {
	      byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
	      _b0 = (byte)(_b0 << 4);
	      byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
	      byte ret = (byte)(_b0 ^ _b1);
	      return ret;
	   }
	   /**
	     * 将指定字符串src，以每两个字符分割转换为16进制形式
	     * 如："2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF, 0xD9}
	     * @param src String
	     * @return byte[]
	     */
	   public  byte[] HexString2Bytes(String src){
	      byte[] ret = new byte[1];
	      byte[] tmp = src.getBytes();
	      for(int i=0; i<1; i++){
	        ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
	      }
	      return ret;
	   }
	
	
	
	
}
